// Package alertconverter provides functions to convert alerts from different sources
// to the unified AlertData format used by the system.
package alertconverter

import (
	"fmt"
	"time"
	"v2/model"
)

// FalcoAlert represents the alert format from Falco
type FalcoAlert struct {
	Output       string                 `json:"output"`
	Priority     string                 `json:"priority"`
	Rule         string                 `json:"rule"`
	Time         string                 `json:"time"`
	OutputFields map[string]interface{} `json:"output_fields"`
}

// ConvertFalcoAlert converts a Falco alert to the unified AlertData format
func ConvertFalcoAlert(falcoAlert FalcoAlert) model.AlertData {
	severity := 4 // 默认为信息级别
	switch falcoAlert.Priority {
	case "Emergency":
		severity = 1
	case "Alert":
		severity = 2
	case "Critical":
		severity = 2
	case "Error":
		severity = 2
	case "Warning":
		severity = 3
	case "Notice":
		severity = 4
	case "Informational":
		severity = 4
	case "Debug":
		severity = 4
	}

	// 解析时间戳
	triggerTime := time.Now().Unix()
	if parsedTime, err := time.Parse("2006-01-02T15:04:05.999999999Z", falcoAlert.Time); err == nil {
		triggerTime = parsedTime.Unix()
	}

	// 构建标签
	tagsMap := make(map[string]string)
	for k, v := range falcoAlert.OutputFields {
		if str, ok := v.(string); ok {
			tagsMap[k] = str
		}
	}
	tagsMap["rule"] = falcoAlert.Rule

	tags := make([]string, 0, len(tagsMap))
	for k, v := range tagsMap {
		tags = append(tags, k+"="+v)
	}

	return model.AlertData{
		ID:            hashStringToInt(falcoAlert.Rule + falcoAlert.Time),
		Cate:          "falco",
		RuleName:      falcoAlert.Rule,
		RuleNote:      falcoAlert.Output,
		TriggerTime:   triggerTime,
		Severity:      severity,
		Tags:          tags,
		TagsMap:       tagsMap,
		FormattedTime: time.Unix(triggerTime, 0).Format("2006-01-02 15:04:05"),
	}
}

// GenerateFalcoCardMessage 生成Falco告警的卡片消息，适用于所有IM渠道
func GenerateFalcoCardMessage(alertData model.AlertData) string {
	// 构建易于阅读的文本格式消息
	message := fmt.Sprintf(
		"Falco安全告警\n\n"+
			"告警规则: %s\n"+
			"触发时间: %s\n"+
			"告警级别: %s\n"+
			"命名空间: %s\n"+
			"Pod名称: %s\n"+
			"告警详情: %s\n"+
			"告警ID: %d",
		alertData.RuleName,
		alertData.FormattedTime,
		getSeverityText(alertData.Severity),
		getStringFromMap(alertData.TagsMap, "k8s.ns.name", "default"),
		getStringFromMap(alertData.TagsMap, "k8s.pod.name", "Unknown"),
		alertData.RuleNote,
		alertData.ID,
	)

	return message
}